package com.leeyu.rabbitmq.workqueues;

import com.leeyu.rabbitmq.util.RabbitMQConnectionUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Consumer {

    private static final String QUEUE_NAME = "work-queues";

    @Test
    public void consume1() throws Exception {
        // 获取连接
        Connection connection = RabbitMQConnectionUtil.getConnection();

        // 构建channel
        Channel channel = connection.createChannel();

        // 构建队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        //每次获取消息数
        channel.basicQos(1);

        // 监听消息
        DefaultConsumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费1号获取到消息：" + new String(body, StandardCharsets.UTF_8));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, callback);

        System.in.read();
    }

    @Test
    public void consume2() throws Exception {
        // 获取连接
        Connection connection = RabbitMQConnectionUtil.getConnection();

        // 构建channel
        Channel channel = connection.createChannel();

        // 构建队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        //每次获取消息数
        channel.basicQos(1);

        // 监听消息
        DefaultConsumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费2号获取到消息：" + new String(body, StandardCharsets.UTF_8));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume(QUEUE_NAME, false, callback);

        System.in.read();
    }
}
